<template>
  <xyEnergyhead>
    <EnergyHead
      title="电费统计"
      icon="dashboard-3"
      :info="info"
      @download-chart="downloadChart"
      @init-chart="initChart"
    >
    </EnergyHead>
    <div class="chart-card">
      <div class="stat-card">
        <div class="stat-label">今日电费</div>
        <div class="stat-value">￥ 875</div>
        <div class="trend-up">
          <span><i class="el-icon-top"></i> 3.5%</span>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-label">本月电费</div>
        <div class="stat-value">￥ 19,915</div>
        <div class="trend-down">
          <span><i class="el-icon-bottom"></i> 1.8%</span>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-label">本年电费</div>
        <div class="stat-value">￥ 227,976</div>
        <div class="trend-down">
          <span><i class="el-icon-bottom"></i> 7.2%</span>
        </div>
      </div>
    </div>
    <div v-if="typeShow" class="chart-container">
      <div ref="electricityChart" class="chart-wrapper"></div>
    </div>
    <div v-if="!typeShow" class="table-view">
      <el-table
        :data="tableData"
        style="width: 100%"
        size="large"
        :header-cell-style="{ background: '#0066ff0d', color: '#0066ff' }"
      >
        <el-table-column prop="date" label="月份"> </el-table-column>
        <el-table-column prop="name" label="用电量(kWh)"> </el-table-column>
        <el-table-column prop="address" label="同比变化">
          <template slot-scope="scope">
            <span :class="scope.row.address === '4.5%' ? 'trend-up' : 'trend-down'"
              ><i
                :class="scope.row.address === '4.5%' ? 'el-icon-top' : 'el-icon-bottom'"
              ></i
              >{{ scope.row.address }}</span
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 详细统计信息 -->
    <el-card class="main-analysis">
      <div class="main-analysis-header">
        <svg-icon icon-class="dashboard-3"></svg-icon>
        <span class="main-analysis-title">电费详细分析</span>
      </div>
      <div class="main-analysis-content">
        <div class="main-analysis-content-item">
          <div>今日最大电费</div>
          <div class="main-analysis-content-item-value">¥ 100 (14:30)</div>
        </div>
        <div class="main-analysis-content-item">
          <div>今日最小电费</div>
          <div class="main-analysis-content-item-value">¥ 19 (03:15)</div>
        </div>
        <div class="main-analysis-content-item">
          <div>今日平均电费</div>
          <div class="main-analysis-content-item-value">¥ 36.5/h</div>
        </div>
        <div class="main-analysis-content-item">
          <div>昨日最大电费</div>
          <div class="main-analysis-content-item-value">¥ 94 (15:00)</div>
        </div>
        <div class="main-analysis-content-item">
          <div>昨日最小电费</div>
          <div class="main-analysis-content-item-value">¥ 17.5 (02:45)</div>
        </div>
        <div class="main-analysis-content-item">
          <div>昨日平均电费</div>
          <div class="main-analysis-content-item-value">¥ 34.7/h</div>
        </div>
      </div>
    </el-card>
  </xyEnergyhead>
</template>

<script>
import xyEnergyhead from "../../components/xy-energy-head.vue";
import EnergyHead from "./EnergyHead.vue";
import * as echarts from "echarts";

export default {
  components: { xyEnergyhead, EnergyHead },
  props: {
    typeShow: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      electricityChart: null,
      currentTimeDimension: "day", // 默认显示年维度数据
      chartData: {
        day: {
          labels: Array.from({ length: 24 }, (_, i) => `${i}:00`),
          data: Array.from({ length: 24 }, (_, i) => {
            // 模拟一天内的电费变化，基于电价策略
            if ((i >= 8 && i <= 12) || (i >= 17 && i <= 21)) {
              // 峰时段电价高
              return 320 + Math.random() * 80;
            } else if (
              (i >= 7 && i <= 8) ||
              (i >= 12 && i <= 17) ||
              (i >= 21 && i <= 22)
            ) {
              // 平时段
              return 220 + Math.random() * 60;
            } else {
              // 谷时段电价低
              return 80 + Math.random() * 50;
            }
          }),
        },
        month: {
          labels: ["第1周", "第2周", "第3周", "第4周"],
          data: [10640, 11060, 10430, 10920],
        },
        year: {
          labels: [
            "1月",
            "2月",
            "3月",
            "4月",
            "5月",
            "6月",
            "7月",
            "8月",
            "9月",
            "10月",
            "11月",
            "12月",
          ],
          data: [
            19950,
            19040,
            17360,
            15750,
            13860,
            12950,
            13440,
            14350,
            16660,
            17850,
            18760,
            19740,
          ],
        },
      },
      tableData: [
        {
          date: "1月",
          name: "650 KWh",
          address: "4.5%",
        },
        {
          date: "2月",
          name: "650 KWh",
          address: "4.5%",
        },
        {
          date: "3月",
          name: "650 KWh",
          address: "4.5%",
        },
        {
          date: "4月",
          name: "650 KWh",
          address: "2.3%",
        },
      ],
      info: {
        title: "电费统计详情",
        listInfo: [
          {
            title: "此图表展示了电费支出的详细统计信息，反映了不同时间段的电费变化。",
          },
          {
            title: "电费数据与电量使用情况密切相关，但也会受到电价政策调整的影响。",
          },
          {
            title: "通过对比不同时间段的电费支出，可以评估节能措施的效果。",
          },
        ],
      },
    };
  },
  mounted() {
    if (this.typeShow) {
      this.$nextTick(() => {
        this.initElectricityChart();
      });
    }
    this.updateTableData();
  },
  beforeDestroy() {
    if (this.electricityChart) {
      this.electricityChart.dispose();
    }
  },
  watch: {
    typeShow: {
      handler(newVal) {
        if (newVal) {
          this.$nextTick(() => {
            this.initElectricityChart();
          });
        } else {
          if (this.electricityChart) {
            this.electricityChart.dispose();
            this.electricityChart = null;
          }
          this.updateTableData();
        }
      },
      immediate: true,
    },
    currentTimeDimension: {
      handler() {
        if (this.typeShow) {
          this.$nextTick(() => {
            this.initElectricityChart();
          });
        } else {
          this.updateTableData();
        }
      },
    },
  },
  methods: {
    initChart() {
      if (this.typeShow) {
        this.initElectricityChart();
      } else {
        this.updateTableData();
      }
    },
    switchTimeDimension(dimension) {
      this.currentTimeDimension = dimension;
    },

    updateTableData() {
      // 表格数据更新逻辑
    },

    initElectricityChart() {
      if (!this.$refs.electricityChart) return;

      if (this.electricityChart) {
        this.electricityChart.dispose();
      }

      this.electricityChart = echarts.init(this.$refs.electricityChart);

      const currentData = this.chartData[this.currentTimeDimension];

      // 使用 ECharts 的 LinearGradient 创建渐变色
      const gradient = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
        { offset: 0, color: "rgba(123, 44, 191, 0.8)" },
        { offset: 1, color: "rgba(123, 44, 191, 0.2)" },
      ]);

      const option = {
        title: {
          text: this.getTimeDimensionTitle(),
          left: "center",
          textStyle: {
            color: "#64748b",
            fontSize: 16,
            fontWeight: "bold",
          },
        },
        tooltip: {
          trigger: "axis",
          formatter: (params) => {
            let result = params[0].name + "<br/>";
            params.forEach((param) => {
              result += `<div style="display:flex;align-items:center;">
            <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${param.color};"></span>
            ${param.seriesName}: ¥${param.value}
          </div>`;
            });
            return result;
          },
        },
        xAxis: {
          type: "category",
          data: currentData.labels,
          axisLine: {
            lineStyle: {
              color: "rgba(0, 102, 255, 0.1)",
            },
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            color: "#64748b",
            rotate: this.currentTimeDimension === "day" ? 0 : 45,
          },
          boundaryGap: true,
        },
        yAxis: {
          type: "value",
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            lineStyle: {
              color: "rgba(0, 102, 255, 0.1)",
            },
          },
          axisLabel: {
            color: "#64748b",
            formatter: (value) => {
              return "¥" + value;
            },
          },
          name: this.getYAxisName(),
          nameTextStyle: {
            color: "#64748b",
            fontSize: 13,
            fontWeight: "bold",
          },
        },
        series: [
          {
            name: this.getSeriesName(),
            type: "bar",
            data: currentData.data,
            smooth: true,
            symbolSize: 8,
            itemStyle: {
              color: gradient, // 使用创建的渐变色
              borderColor: "#7b2cbf",
              borderWidth: 1,
              borderRadius: [8, 8, 0, 0], // 上边圆角
              borderSkipped: false,
            },
            emphasis: {
              focus: "series",
              itemStyle: {
                borderColor: "#fff",
                borderWidth: 2,
                shadowColor: "rgba(0, 0, 0, 0.3)",
                shadowBlur: 5,
              },
            },
            barWidth: "60%",
          },
        ],
        grid: {
          left: "5%",
          right: "5%",
          bottom: "15%",
          top: "20%",
          containLabel: true,
        },
        color: ["#7b2cbf"],
      };

      this.electricityChart.setOption(option);
      window.addEventListener("resize", this.handleResize);
    },

    getTimeDimensionTitle() {
      const titles = {
        day: "24小时电费统计",
        month: "月电费统计",
        year: "年度电费统计",
      };
      return titles[this.currentTimeDimension];
    },

    getValueUnit() {
      return "元";
    },

    getYAxisName() {
      return "电费 (元)";
    },

    getSeriesName() {
      const names = {
        day: "小时电费",
        month: "周电费",
        year: "月电费",
      };
      return names[this.currentTimeDimension];
    },

    handleResize() {
      if (this.electricityChart) {
        this.electricityChart.resize();
      }
    },
    downloadChart() {
      if (!this.electricityChart) {
        console.error("图表实例不存在");
        return;
      }

      try {
        // 使用 ECharts 的 getDataURL 方法获取图片数据
        const dataURL = this.electricityChart.getDataURL({
          type: "png",
          pixelRatio: 2,
          backgroundColor: "#fff",
        });

        // 创建下载链接
        const link = document.createElement("a");
        link.download = `电费统计图表_${new Date().getTime()}.png`;
        link.href = dataURL;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      } catch (error) {
        console.error("下载图表失败:", error);
        // 如果需要，可以显示错误消息
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./EnergyAnalysis.scss";

.chart-container {
  padding: 20px;
}

.chart-wrapper {
  width: 100%;
  height: 400px;
}

.chart-card {
  display: flex;
  justify-content: space-between;
  gap: 20px;

  .stat-card {
    flex: 1;
    margin: 15px 0;
    position: relative;
    background: linear-gradient(
      135deg,
      rgba(0, 102, 255, 0.05) 0%,
      rgba(123, 44, 191, 0.05) 100%
    );
    border-radius: 12px;
    padding: 18px;
    transition: all 0.3s;
    border: 1px solid rgba(0, 102, 255, 0.1);
    overflow: hidden;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
  }

  .stat-card::before {
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    height: 4px;
    width: 100%;
    background: linear-gradient(90deg, #0066ff, #7b2cbf);
  }

  .stat-label {
    font-size: 0.9rem;
    color: #64748b;
    font-weight: 500;
    text-align: center;
    margin-bottom: 8px;
  }

  .stat-value {
    font-size: 1.8rem;
    font-weight: 700;
    color: #0055ff;
    margin: 10px 0;
    text-align: center;
  }
}

.trend-up {
  color: #10b981;
  font-weight: 500;
  font-size: 0.85rem;
  text-align: center;

  i {
    margin-right: 3px;
  }
}

.trend-down {
  color: #ef4444;
  font-weight: 500;
  font-size: 0.85rem;
  text-align: center;

  i {
    margin-right: 3px;
  }
}

.table-view {
  border-radius: 12px;
  border: 1px solid rgba(0, 102, 255, 0.1);
}

.main-analysis {
  margin-top: 20px;
  border-radius: 12px;
  border: 1px solid rgba(0, 102, 255, 0.1);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
}

.main-analysis-header {
  display: flex;
  align-items: center;
  font-size: 1.2rem;
  font-weight: 600;
  color: #0055ff;
  margin-bottom: 20px;

  .svg-icon {
    margin-right: 10px;
    font-size: 1.3rem;
    width: 1.3rem;
    height: 1.3rem;
  }
}

.main-analysis-content {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.main-analysis-content-item {
  background: #f8fafc;
  padding: 15px;
  border-radius: 8px;
  border: 1px solid #e2e8f0;

  div:first-child {
    font-size: 0.9rem;
    color: #64748b;
    margin-bottom: 8px;
  }

  .main-analysis-content-item-value {
    font-size: 1.1rem;
    font-weight: 600;
    color: #0055ff;
  }
}

@media (max-width: 768px) {
  .chart-card {
    flex-direction: column;

    .stat-card {
      width: 100%;
      margin-bottom: 15px;
    }
  }

  .main-analysis-content {
    grid-template-columns: 1fr;
  }

  .chart-wrapper {
    height: 300px;
  }
}
</style>
